package com.youme.util

import android.content.Context
import android.net.ConnectivityManager
import android.text.TextUtils
import java.util.regex.Pattern

/**
 * @Time:2021/3/19 15:23
 * @Author:wujinsheng
 * @Description:
 */
object Utils {
    // This pattern comes from android.util.Patterns. It has been tweaked to handle a "1" before
    // parens, so numbers such as "1 (425) 222-2342" match.
    private val PHONE_PATTERN = Pattern.compile( // sdd = space, dot, or dash
        "(\\+[0-9]+[\\- \\.]*)?" // +<digits><sdd>*
            + "(1?[ ]*\\([0-9]+\\)[\\- \\.]*)?" // 1(<digits>)<sdd>*
            + "([0-9][0-9\\- \\.][0-9\\- \\.]+[0-9])") // <digit><digit|sdd>+<digit>

    /**
     * Returns true if the string is a phone number.
     */
    @JvmStatic
    fun isPhoneNumber(number: String?): Boolean {
        // TODO: replace this function with libphonenumber's isPossibleNumber (see
        // PhoneNumberUtil). One complication is that it requires the sender's region which
        // comes from the CurrentCountryIso. For now, let's just do this simple match.
        if (TextUtils.isEmpty(number)) {
            return false
        }
        val match = PHONE_PATTERN.matcher(number)
        return match.matches()
    }

    fun isNetworkDisconnect(context: Context?): Boolean {
        return !isNetworkConnected(context)
    }

    fun isNetworkConnected(context: Context?): Boolean {
        context?.let {
            val mConnectivityManager =
                it.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val mNetworkInfo = mConnectivityManager.activeNetworkInfo
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable
            }
        }
        return false
    }
}